package crp.core.security.domain.services.caller;

import com.google.common.base.Suppliers;
import com.qwlabs.security.Caller;
import com.qwlabs.security.CallerPermissions;
import crp.core.security.Callers;
import crp.core.security.domain.services.PermissionLoader;
import lombok.AllArgsConstructor;
import lombok.Builder;

import javax.validation.constraints.NotNull;
import java.util.Set;
import java.util.function.Supplier;

@Builder
@AllArgsConstructor
public class UserCallerPermissions implements CallerPermissions {
    private final Caller caller;
    private final PermissionLoader permissionLoader;
    private final Supplier<Set<String>> rawSupplier = Suppliers.memoize(this::loadRaw);

    @Override
    public Set<@NotNull String> raw() {
        return rawSupplier.get();
    }

    @Override
    public @NotNull Set<@NotNull String> raw(@NotNull String scope) {
        return rawSupplier.get();
    }

    @Override
    public boolean has(String permissions) {
        return raw().contains(permissions);
    }

    @Override
    public @NotNull boolean has(@NotNull String scope, @NotNull String permission) {
        return has(permission);
    }

    private Set<String> loadRaw() {
        return permissionLoader.load(Callers.userId(caller));
    }
}
